package utils;

import gamehistory.utils.xml.XMLModel;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * 
 * @author Brent Kersanske
 *
 */
public class FileUtilities {
	
	private static final String MSG_INFO_FORMATTED_FILE_CREATED   = "[INFO] Created {0}.";
	private static final String MSG_ERROR_EXCEPTION_WHILE_WRITING = "[ERROR] Encountered an exception while trying to write file {0}: {1}";
	
	public static final String XML_HEADER	 = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
	public static final String XML_FILE_TYPE = ".xml";
	
	/**
	 * 
	 * @param directoryName
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static ArrayList<String> getFileNamesInDirectory(String directoryName) throws IllegalArgumentException {
        File directory 			= new File(directoryName);  
        if(!directory.isDirectory()) {
        	throw new IllegalArgumentException(directoryName + " is not a directory!");
        } 
		ArrayList<String> files = new ArrayList<String> ();
		for (int i = 0; i < directory.list().length; i++) {
			files.add(directory.list()[i]);
		}
		return files;
     }
	
	/**
	 * 
	 * @param directoryName
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static ArrayList<String> getDirectoryNamesInDirectory(String directoryName) throws IllegalArgumentException {
		ArrayList<String> directories = new ArrayList<String> ();
		File directory 				  = new File(directoryName);
		if(!directory.isDirectory()) {
			throw new IllegalArgumentException(directoryName + " is not a directory!");
		}
		for(String subdirectory : directory.list()) {
			File potentialSubdirectory = new File(subdirectory);
			if(potentialSubdirectory.isDirectory()) {
				directories.add(subdirectory);
			}
		}
		return directories;
	}
	
    /**
     * 
     * @param fileOut
     */
    public static void writeXMLToFile(XMLModel completedModel, String fileOutDirectory, String fileOutName) {
		try {
			fileOutName 	   = fileOutName.concat(XML_FILE_TYPE);
			String fileOut 	   = fileOutDirectory.concat(fileOutName);
			BufferedWriter out = new BufferedWriter(new FileWriter(fileOut));
			out.write(FileUtilities.XML_HEADER + "\n");
			out.write(completedModel.getModel());
	        out.close();	
	        System.out.println(MessageFormat.format(MSG_INFO_FORMATTED_FILE_CREATED, fileOutName));	
		} catch(Exception e) {
			System.out.println(MessageFormat.format(MSG_ERROR_EXCEPTION_WHILE_WRITING, fileOutName, e.getMessage()));
		}
	}

}
